<?php

/**
 * ObjectModel for fiche database table. 
 * @author Nicolas Legrand <n.legrand28@gmail.com>
 */
class Fiche extends ObjectModel
{
	public $id_fiche;
	public $id_customer;
	public $type;
	public $name;
	public $data;
	public $date;
	public $date_modif;
	public $weight;
	public $modelId;
	public $propId;
	public $public;
	public $theme;
	public $format;
	public $orientation;
	public $active;
	public $rent;
	
	// LVM
	public $groupname_fiche;
	
	const WEIGHT_MODULATOR = 1048576; /*1024 * 1024*/
	
	const ACTIVE = 1;
	const INACTIVE = 0;
	
	const RENT = 1;
	const SELL = 0;
	
	const FICHE = 0;
	const FICHE_MODELE = 1;
	
	const PUBLIC_FICHE = 0;
	const PRIVATE_FICHE = 1;		
	
	const LANDSCAPE = 0;
	const PORTRAIT = 1;
	
	const DEFAULT_FORMAT = 'A4';
	
	const ALL = 1000000;
	
	public static function rewriteDynamicTranslations()
	{
		$themes = FicheTheme::findAll();
		$props = FicheProp::findAll();
		
		$data = '<div class="fichevitrine_module">';
		$data .= "\n";
		
		foreach( $themes as $theme )
		{
			$data.= "{l s=\"".$theme->name."\" mod='fichevitrine'}\n";
		}
		
		foreach( $props as $prop )
		{
			$data.= "{l s=\"".$prop->name."\" mod='fichevitrine'}\n";
		}
		
		$data .= "</div>";
		
		$path = _PS_MODULE_DIR_.'fichevitrine/views/templates/front/translations.tpl';
		file_put_contents($path, $data );
	}
	
	// LVM
	public static function getOrientations($btrad=true)
	{
		if ($btrad)
		{
			$tab = array(Fiche::getName("Paysage_H") => Fiche::LANDSCAPE, Fiche::getName("Portrait_V") => Fiche::PORTRAIT);
		}
		else
			$tab = array("Paysage_H" => Fiche::LANDSCAPE, "Portrait_V" => Fiche::PORTRAIT);	
			
		return $tab;	
	}
	
	// LVM
	public static function getDomains($btrad=true)
	{
		if ($btrad)
			$tab = array(Fiche::getName("Public") => Fiche::PUBLIC_FICHE, Fiche::getName("Privé") => Fiche::PRIVATE_FICHE);
		else
			$tab = array("Public" => Fiche::PUBLIC_FICHE, "Privé" => Fiche::PRIVATE_FICHE);	
			
		return $tab;
	}
	
	// LVM
	public static function getTypes($btrad=true)
	{
		if ($btrad)
			$tab = array(Fiche::getName("Fiche") => Fiche::FICHE, Fiche::getName("Modèle") => Fiche::FICHE_MODELE);
		else
			$tab = array("Fiche" => Fiche::FICHE, "Modèle" => Fiche::FICHE_MODELE);
			
		return $tab;
	}
	
	// LVM
	public static function getTransacts($btrad=true)
	{	
		if ($btrad)
			$tab = array(Fiche::getName("Vente") => Fiche::SELL, Fiche::getName("Location") => Fiche::RENT);
		else
			$tab = array("Vente" => Fiche::SELL, "Location" => Fiche::RENT);
			
		return $tab;
	}
	
	// LVM
	public static function getName($name)
	{
		$trad = Translate::getModuleTranslation('fichevitrine', $name, 'translations');
		
		//echo 'trad = '.$trad.'---';
		
		return $trad;
	}
	
	public static function getFormats()
	{
		return array(
		'A0' => array(841,1189),
		'A1' => array(594,841), 
		'A2' => array(420,594),
		'A3' => array(297,420),
		'A4' => array(210,297), 
		'A5' => array(148,210), 
		'A6' => array(105,148), 
		'A7' => array(74,105), 
		'A8' => array(52, 74), 
		'Letter' => array(216, 279), 
		'Legal' => array(216, 356), 
		'Ledger' => array(279,432),
		'Tabloid' => array(279,432), 
		'ANSI A (letter)' => array(216, 279), 
		'ANSI B (ledger)' => array(279,432), 
		'ANSI B (tabloid)' => array(279, 432), 
		'ANSI C' => array(432, 559), 
		'ANSI D' => array(559, 864), 
		'ANSI E' => array(864, 1118), 
		'ANSI F' => array(711, 1016), 
		'Statement Half Letter' => array(140, 216), 
		'Quarto' => array(203, 254), 
		'Foolscap (folio)' => array(210, 330), 
		'Super-B' => array(330, 483), 
		'Post' => array(394, 489), 
		'Crown' => array(381, 508), 
		'Demy' => array(445, 572), 
		'Medium' => array(457, 584), 
		'Broadsheet' => array(457, 610), 
		'Royal' => array(508, 635), 
		'Elephant' => array(584, 711), 
		'Double Demy' => array(572, 889), 
		'Quad Demy' => array(889, 1143)
	);
	}
	
	public static function getFormatsInPt()
	{
		$tab = array();
		foreach( Fiche::getFormats() as $key => $value )
		{
			$tab[$key] = array( (int)($value[0] * 2.83), (int)($value[1] * 2.83) );
		}
		
		return $tab;
	}
	
	public static function getFormatSize($userFormat)
	{
		$format = array(1, 1);
		$formats = Fiche::getFormats();
		
		if ( isset($formats[$userFormat] ) )
		{
			$format = $formats[$userFormat];
		}
		else
		{
			$format = $formats[Fiche::DEFAULT_FORMAT];
		}
		
		//$convert = 0.2645833333333;
		$dpi = 135;
		$convert = $dpi / 2.54 / 10;
		$width = (int)($format[0] * $convert);
		$height = (int)($format[1] * $convert);
		
		return array($width,$height);
	}
	
	
	public static function getManURI()
	{
		// LVM
		//return _MODULE_DIR_.'fichevitrine/doc/Manuel_FicheVitrine_VitrineMedia.pdf';
		
		//$link = Context::getContext()->Link;
		
		//var_dump($link);
		
		$path = _PS_ROOT_DIR_.'/'._MODULE_DIR_.'fichevitrine/doc/';
		
		$filename = $path.'Manuel_FicheVitrine_VitrineMedia_';
		
		// Code langue ?
		//var_dump(Context::getContext()->language);
		
		$code_lang = Context::getContext()->language->iso_code;
		
		$filename .= $code_lang;
		
		$filename .= '.pdf';
		
		// Test existence fichier
		if (!is_file($filename))
		{
			//$path = _PS_ROOT_DIR_.'/'._MODULE_DIR_.'fichevitrine/doc/';
			$path = _MODULE_DIR_.'fichevitrine/doc/';
		
			$filename = $path.'Manuel_FicheVitrine_VitrineMedia_';
		
			// Langue par défaut
			$code_lang = 'en';
		
			$filename .= $code_lang;
			
			$filename .= '.pdf';	
		}
		else
		{
			$path = _MODULE_DIR_.'fichevitrine/doc/';
		
			$filename = $path.'Manuel_FicheVitrine_VitrineMedia_';
		
			$code_lang = Context::getContext()->language->iso_code;
		
			$filename .= $code_lang;
		
			$filename .= '.pdf';	
		}
		
		return $filename;
	}
	
	public static $definition = array(
	
  		'table' 	=> 'fiche',
  		'primary' 	=> 'id_fiche',
  		'multilang' => false,
 		'fields' => array(
   			'id_fiche' => array(
   				'type' => ObjectModel :: TYPE_INT
			),
			'id_customer' => array(
   				'type' => ObjectModel :: TYPE_INT, 
   				'required' => true
			),
			'weight' => array(
   				'type' => ObjectModel :: TYPE_INT, 
   				'required' => true
			),
			'modelId' => array(
   				'type' => ObjectModel :: TYPE_INT, 
   				'required' => true
			),
			'propId' => array(
   				'type' => ObjectModel :: TYPE_INT, 
   				'required' => true
			),
			'name' => array(
   				'type' => ObjectModel :: TYPE_STRING, 
   				'required' => true
			),
			'type' => array(
   				'type' => ObjectModel :: TYPE_INT, 
   				'required' => true
			),
			'active' => array(
   				'type' => ObjectModel :: TYPE_INT, 
   				'required' => true
			),
			'data' => array(
   				'type' => ObjectModel :: TYPE_STRING, 
   				'required' => true
			),
			'date' => array(
   				'type' => ObjectModel :: TYPE_DATE, 
   				'required' => false
			),
			'date_modif' => array(
   				'type' => ObjectModel :: TYPE_DATE, 
   				'required' => false
			),
			'public' => array(
   				'type' => ObjectModel :: TYPE_INT, 
   				'required' => true
			),
			'theme' => array(
   				'type' => ObjectModel :: TYPE_INT, 
   				'required' => true
			),
			'format' => array(
   				'type' => ObjectModel :: TYPE_STRING, 
   				'required' => true
			),
			'orientation' => array(
   				'type' => ObjectModel :: TYPE_INT, 
   				'required' => true
			),
			'rent' => array(
   				'type' => ObjectModel :: TYPE_INT, 
   				'required' => true
			)
  		)
	);
	
	public static function getTotalFicheWhere($conditions,$activeOnly = true)
	{
		if ($activeOnly == true)
		{
			$conditions['active'] = Fiche::ACTIVE;
		}
		
		$sql = 'SELECT COUNT(id_fiche) as total FROM ' . _DB_PREFIX_ . 'fiche '.Fiche::buildWhereClause($conditions);
		
		$total = 0;
		
		if ($rows = Db :: getInstance()->ExecuteS($sql)) {
			$total = (int)($rows[0]['total']);
		}
		
		return $total;
	}
	
	public static function getDefaultFicheName($customer_id)
	{
		return 'Fiche n°'.( Fiche::getTotalFicheWhere(array("type"=>Fiche::FICHE, "id_customer"=>$customer_id)) + 1 );
	}
	
	public static function getDefaultModelName($customer_id)
	{
		return 'Modele n°'.( Fiche::getTotalFicheWhere(array("type"=>Fiche::FICHE_MODELE, "id_customer"=>$customer_id)) + 1 );
	}
	
	public static function getLastFiche()
	{
		$fiche = null;
		
		$sql = 'SELECT * FROM '._DB_PREFIX_.'fiche ORDER BY id_fiche DESC LIMIT 1';
		
		if ($rows = Db :: getInstance()->ExecuteS($sql)) {
			$collec = ObjectModel :: hydrateCollection(__CLASS__, $rows);
			
			if ( count($collec) > 0 )
				$fiche = $collec[0];
		}
		
		return $fiche;
	}
	
	public static function addFiche( 	$name, 
										$type, 
										$customerId, 
										$modelId, 
										$rentId,
										$propId, 
										$themeId = -1, 
										$public = false, 
										$format = null, 
										$orientation = null,
										$active = true
	)
	{
		$publicValue = ( $public == true ) ? Fiche::PUBLIC_FICHE : Fiche::PRIVATE_FICHE;
		$activeValue = ( $active == true ) ? Fiche::ACTIVE : Fiche::INACTIVE;
		$formatValue = ( $format == null ) ? Fiche::DEFAULT_FORMAT : $format;
		$orientationValue = ( $orientation == null ) ? Fiche::LANDSCAPE : $orientation;
		$results = Fiche::findFicheBy( array(
			'id_fiche'=>(int)($modelId)
		));
		
		$fiche = new Fiche();
		$fiche->id_customer = (int)($customerId);
		$fiche->type = (int)($type);
		$fiche->data = '[]';
		$fiche->date = date('Y-m-d H:i:s');
		$fiche->date_modif = date('Y-m-d H:i:s');
		$fiche->name = $name;
		$fiche->modelId = $modelId;
		$fiche->rent = $rentId;
		$fiche->propId = $propId;
		$fiche->weight = 0;
		$fiche->theme = $themeId;
		$fiche->format = $formatValue;
		$fiche->orientation = $orientationValue;
		$fiche->public = $publicValue;
		$fiche->active = $activeValue;
			
		$fiche->add();
		
		if (count($results) > 0)
		{
			$model = $results[0];
			$fiche->id_fiche = Db::getInstance()->Insert_ID();
			$fiche->data = $model->data;
			$fiche->weight = $model->weight;
			
			$modelDir = $model->getFicheDir();
			$ficheDir = $fiche->getFicheDir();
			$list = scandir($modelDir);
			
			foreach ($list as $currentFile)
			{
				if ( 	$currentFile == '..' || $currentFile == '.' ||  !is_file($modelDir.'/'.$currentFile) )
					continue;
					
				
				if ( strpos($currentFile, 'preview') === false )
				{
					$imgData = file_get_contents($modelDir.'/'.$currentFile);
					file_put_contents($ficheDir.'/'.$currentFile, $imgData);
				}
			}
			
			$fiche->save();
		}
	}
	
	
	public function getUsedTextures($data)
	{
		$results = array();

		foreach($data as $dataChild)
		{
			if( isset($dataChild->textureName))
			{
				$results[]=$dataChild->textureName;
			}
		}
		
		return $results;
	}
	
	public function cleanFicheDir()
	{
		$data = json_decode($this->data);
		$textures = $this->getUsedTextures($data);
		$info = null;
		$dir = $this->getFicheDir();
		
		$list = scandir($dir);
		
		//clean directory
		foreach( $list as $currentFile )
		{
			if ( $currentFile != '..' && $currentFile != '.' && is_file($dir.'/'.$currentFile))
			{
				if ( in_array($currentFile, $textures) != 1 )
				{
					if( strpos($currentFile,'preview') === false )
						unlink($dir.'/'.$currentFile);
				}
			}
		}
	}
	
	public function calcWeight()
	{
		$weight = 0;
		$info = null;
		$dir = $this->getFicheDir();
		$list = scandir($dir);
		
		//clean directory
		foreach( $list as $currentFile )
		{
			if ( $currentFile != '..' && $currentFile != '.' && is_file($dir.'/'.$currentFile))
			{				
				$info = stat($dir.'/'.$currentFile);
				$weight += (int)($info[7]);
			}
		}
		
		return $weight;
	}
	
	public function addPreview($imgData)
	{
		$parts = explode(',',$_POST['preview']);
		$data = $parts[1];
		$data = str_replace(' ', '+', $data);
		$data = base64_decode($data); 
		$dir = $this->getPreviewDir();
		$filePath = $dir.'/preview_'.$this->id_customer.'_'.$this->id_fiche.'.png';
		file_put_contents($filePath,$data);
	}
	
	public function getPreviewDir()
	{
		return $this->getFicheDir();
	}
	
	public function getFicheURI()
	{
		return _MODULE_DIR_.'fichevitrine/data/users/user_'.$this->id_customer.'/fiche_'.$this->id_fiche.'/';
	}	
	
	public function getPreview()
	{
		return $this->getFicheURI().'preview_'.$this->id_customer.'_'.$this->id_fiche.'.png';
	}
	
	public function getUserDir()
	{
		$dir = _PS_MODULE_DIR_.'fichevitrine/data/users/user_'.$this->id_customer;
		if ( file_exists($dir) === false )
		{
			mkdir($dir,0777);
		}
		return $dir;
	}
	
	public function getFicheDir()
	{
		$dir = $this->getUserDir().'/fiche_'.$this->id_fiche;
		if ( file_exists($dir) === false )
		{
			mkdir($dir,0777);
		}
		return $dir;
	}
	
	public function addImage($imgData,$imgName)
	{
		$dir = $this->getFicheDir();
		
		$parts = explode(',',$imgData);
		$data = $parts[1];
		$data = str_replace(' ', '+', $data);
		$data = base64_decode($data); 
		
		$filePath = $dir.'/'.$imgName;
		file_put_contents($filePath, $data);
	}
	
	public function kill()
	{
		$dir = $this->getFicheDir();
		$list = scandir($dir);
		
		foreach( $list as $currentFile )
		{
			if ( $currentFile == "." || $currentFile == ".." )
				continue;
				
			unlink($dir.'/'.$currentFile);
		}
		
		rmdir($dir);
		$this->active = Fiche::INACTIVE;
		$this->weight = 0;
		$this->update();
		
		//$sql = 'DELETE FROM ' . _DB_PREFIX_ . 'fiche WHERE id_fiche = '.(int)($this->id_fiche);
		//Db :: getInstance()->Execute($sql);
	}
	
	public function getModelName()
	{
		$results = Fiche::findFicheBy( array(
			'id_fiche'=>(int)($this->modelId)
		));
		
		if ( count($results) > 0 )
		{
			$model = $results[0];
			return $model->name;
		}
		else
		{
			return "";
		}
	}

	public function getRealFormatSize()
	{
		$size = Fiche::getFormatSize($this->format);
		return $size;
	}
	
	public function getRealWidth()
	{
		$size = $this->getRealFormatSize();
		return $size[0];
	}
	
	public function getRealHeight()
	{
		$size = $this->getRealFormatSize();
		return $size[1];
	}
	
	public static function killFicheById($id)
	{
		$fiches = Fiche::findFicheBy(array('id_fiche' => (int)($id)));
		if ( count($fiches) > 0)
		{
			$fiches[0]->kill();
		}
		//$sql = 'DELETE FROM ' . _DB_PREFIX_ . 'fiche WHERE id_fiche = '.(int)($id);
		//Db :: getInstance()->Execute($sql);
	}
	
	public static function getTotalWeight($customer)
	{
		$sql = 'SELECT SUM(weight) as total FROM ' . _DB_PREFIX_ . 'fiche WHERE id_customer = '. (int)($customer->id);
		$total = 0;
		if ($rows = Db :: getInstance()->ExecuteS($sql)) {
			$total = (int)($rows[0]['total']);
		}
		
		return $total;
	}
	
	public static function findAll() 
	{
		$sql = 'SELECT * FROM ' . _DB_PREFIX_ . 'fiche ORDER BY date_modif DESC';
		if ($rows = Db :: getInstance()->ExecuteS($sql)) {
			$collection = ObjectModel :: hydrateCollection(__CLASS__, $rows);
		}
		return array();
	}
	
	// LVM : addition de la table avec un préfixe pour gérer les cas de requête sur plus d'une table à la fois...
	//public static function buildWhereClause($conditions)
	public static function buildWhereClause($conditions, $prefixetable='')
	{
		$whereClause = '';
		$i = 0;
		
		foreach( $conditions as $key => $value )
		{
			if ( $i == 0 )
			{
				$whereClause .= ' WHERE	';
			}
			else
			{
				if ( is_array($value) && isset($value['conditionnal']) )
				{
					$whereClause .= ' '.$value['conditionnal'].' ';
				}
				else
				{
					$whereClause .= ' AND ';
				}
			}
			//$whereClause .= ($i == 0) ? ' WHERE ' : ' AND ';
			
			if ( is_array($value) )
			{
				// LVM
				if ($prefixetable)
					$whereClause .= $prefixetable.'.';
				//
					
				if ( $value['operator'] == 'LIKE' )
				{	
					$whereClause .= $value['column']." LIKE '%".$value['value']."%'";
				}
				else
				{
					$whereClause .= $value['column']." ".$value['operator']." '".$value['value']."'";
				}
			}
			else
			{
				// LVM : gérer les cas de filtrage tous (public + privé)...
				//$whereClause .= $key." = '".$value."'";
				$pos1 = stripos($value, '(');
				$pos2 = stripos($value, ')');
							
				if (is_int($pos1) == true && is_int($pos2) == true)
				{
					// LVM : le préfixe de la table doit être indiqué avant...
					$whereClause .= $value;
				}
				else
				{
					// LVM
					if ($prefixetable)
						$whereClause .= $prefixetable.'.';
					//
					
					$whereClause .= $key." = '".$value."'";
				}
			}
			
			$i++;
		}
		
		return $whereClause;
	}
	
	
	public static function findFicheById($id)
	{
		$fiches = Fiche::findFicheBy(array('id_fiche' => (int)($id)));
		if ( count($fiches) > 0)
		{
			return $fiches[0];
		}
		
		return null;
	}
	
	public static function findFicheBy ($conditions, 
										$start = -1, 
										$end = -1, 
										$orderBy = 'date_modif', 
										$asc = false,
										$activeOnly = true)
	{
	
		if ( $activeOnly == true )
		{
			$conditions['active'] = Fiche::ACTIVE;
		}
	
		// LVM : gérer la visibilité des modèle/fiche par groupe de user Prestashop
		//$sql = 'SELECT * FROM ' . _DB_PREFIX_ . 'fiche '.Fiche::buildWhereClause($conditions);
		
		// Pas sûr de devoir déclarer customer_group ici car sera déclaré dans des select dans les conditions de addmodel.php...
		//$sql = 'SELECT f.* FROM ' . _DB_PREFIX_ . 'fiche as f, '. _DB_PREFIX_ . 'customer_group as cg';
		//$sql = 'SELECT f.* FROM ' . _DB_PREFIX_ . 'fiche as f';
		if (isset($conditions['special_parenthese_modele_public']))
		{
			//$sql = 'SELECT DISTINCT f.*, gl.name as group_name_user_connected, gl4.name as group_name_fiche';
			$sql = 'SELECT DISTINCT f.*, gl.name as groupname_fiche';
			$sql .= ' FROM ' . _DB_PREFIX_ . 'fiche as f, '. _DB_PREFIX_ . 'customer_group as cg, '. _DB_PREFIX_ . 'group_lang as gl';
			
			//$sql .= ', '. _DB_PREFIX_ . 'customer_group as cg4';
			//$sql .= ', '. _DB_PREFIX_ . 'group_lang as gl4';
		}
		else
		{
			$sql = 'SELECT DISTINCT f.* FROM ' . _DB_PREFIX_ . 'fiche as f';
		}
			
		//$sql .= ' LEFT JOIN '._DB_PREFIX_ .'customer_group as cg ON cg.id_customer = f.id_customer';
		//$sql .= ' LEFT JOIN '._DB_PREFIX_ .'group_lang as gl ON gl.id_group = cg.id_group';
		
		// LVM
		//$sql .= Fiche::buildWhereClause($conditions);
		$sql .= Fiche::buildWhereClause($conditions, $prefixetable = 'f');
		
		$sens = ( $asc == true ) ? 'ASC':'DESC';
		$sql .= ' ORDER BY '.$orderBy.' '.$sens;
		
		if ( $start != -1 || $end != -1)
		{
			$sql .= ' LIMIT '.$start.', '.$end;
		}
		
		// LVM
		//echo 'sql = '.$sql.'---';
		
		if ($rows = Db :: getInstance()->ExecuteS($sql)) {
			return ObjectModel :: hydrateCollection(__CLASS__, $rows);
		}
		
		return array();
	}
	
	// LVM
	public static function getIdCustomerListNotInGroupLFV ($id_lang=5)
	{
		$sql = 'SELECT DISTINCT f3.id_customer FROM ' ._DB_PREFIX_ . 'fiche as f3';
		$sql .= ' WHERE f3.id_customer NOT IN (SELECT DISTINCT f2.id_customer FROM ' ._DB_PREFIX_ . 'fiche as f2, '.  _DB_PREFIX_ . 'group_lang as gl2, '. _DB_PREFIX_ . 'customer_group as cg2';
		$sql .= ' WHERE f2.id_customer = cg2.id_customer';
		$sql .= ' AND gl2.id_group = cg2.id_group';
		$sql .= " AND gl2.name LIKE 'LFV%'";
		$sql .= ' AND gl2.id_lang = '.$id_lang.')';
		
		$list = '';
		
		if ($rows = Db :: getInstance()->ExecuteS($sql)) 
		{
			foreach ($rows as $row)
			{
				$list .= (string)($row['id_customer']);
				$list .= ', ';
			}
			
			$list = trim ($list, ', ');
			
			return $list;
		}
				
		return $list;
	}
	
}
